<template>
<div class="custom-search newBusinessSideBar">
  <div class="table-wrap" v-if="!businessOperation">
    <div class='table-wrap-top'>
      <div class='table-wrap-top-mask' v-if="isNoediting"></div>
      <div class='table-wrap-top-left'>
        <div class="table-wrap-add">
          <span @click='businessAdd'><i class='iconfont icon-zhankai'></i>新建</span>
          <span @click='businessRefresh'><i class='iconfont icon-shuaxin'></i>刷新</span>
        </div>
        <div class='table-wrap-top-search'>
          <input-search  style='width:210px' class='table-wrap-top-search-input' @quickSearch="nomalSearch" :placeHolder="search.placeHolder" :form="search[activeName].isChildren.nomalForm"></input-search>
          <advanced-search
            @ifRemark="ifRemark"
            v-if="search[activeName].isChildren.adv"
            :adv="search[activeName].isChildren.adv"
            :badge="search[activeName].isChildren.adv.badgeList"
            :formItemsConfig="formItemsConfigs && formItemsConfigs[activeName]"
            :activeName="activeName"
            :isNewView="true"
            @selectChange="handlerSelectChange"
            @advSearch="advSearch"
            @resetForm="resetAdvSearch"
            @confirmNewItemsConfig="handleConfirmNewItemsConfig"
          ></advanced-search>
        </div>
        <v-select :selectOptions="businessTypes"
                    :filterable='true'
                    v-show ='activeName !== "business_all"'
                    @quickSelect="handlerQuickSelect"
                    :form="search[activeName].currentSelect"
                    @show="selectShow"
                    :placeholder='"请选择工单类型"'
                    :selectStyle='"width:140px"'
                    :noChange="noChange">
          </v-select>
      </div>
      <div class='table-wrap-top-right'>
          <pagination class="page"
            :small="true"
            :moreFlag="pagination.moreFlag"
            :currentPage="pagination.currentPage"
            :count="pagination.count || 0"
            :later="laterProcessData.length>0"
            @turnPage="turnPage"
            @getAllCount="getAllCount"
            :showPage='false'
            :totalPage="totalPage">
        </pagination>
      </div>
    </div>
    <div>
      <advSchBadge :remark="search[activeName].partakeAgentRemark" v-if="search[activeName].isChildren.adv.badgeList" :badge="search[activeName].isChildren.adv.badgeList" @removeBadge="removeBadge"></advSchBadge>
    </div>
    <BusinessTable ref="businessTable" :tableHeader="tableHeader" :tableData="cardListRender" @operate="operate" :qu='qu' @selectionchange='selectionchange' @selectionall='selectionall'></BusinessTable>
    <div class="batch" :class="{'show': batch.isBatchShow, 'navMenuState': navMenuState}">
      <el-checkbox v-model.trim="batch.allChecked" @change="selectAll">{{$t('public.checkAll')}}</el-checkbox>
      <card-batch v-if="batch.operator"
                  :tabType="activeName"
                  :batchOperator="batch"
                  @exportExcel="exportCustom"
                  @deleteTip="deleteTip"
                  @checkNone="checkNone"
                  @batchAssign="batchAssign"
                  @batchReceive="batchReceive"
        >
        <template slot="batchAssign">
          <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.businessBatchAssign">
            <div class="novice-circle-group " style="position: absolute;top: 3px;right: -23px">
              <div class="novice-circle4"></div>
              <div class="novice-circle3"></div>
              <div class="novice-circle2"></div>
              <div class="novice-circle1"></div>
            </div>
            <div style="position: absolute;top: -90px;left:0 ;padding-bottom: 10px;z-index: 100;">
              <novice-boot
                NoviceKey="businessBatchAssign"
                :NoviceArr="[{title: '', text: $t('business.assignHelp')}]"
                @updateGuidanceSuccess="updateGuidanceSuccess"
              ></novice-boot>
            </div>
          </div>
        </template>
        <template slot="batchExecute">
          <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.businessBatchExecute">
            <div class="novice-circle-group " style="position: absolute;top: 3px;right: -23px">
              <div class="novice-circle4"></div>
              <div class="novice-circle3"></div>
              <div class="novice-circle2"></div>
              <div class="novice-circle1"></div>
            </div>
            <div style="position: absolute;top: -90px;left:0 ;padding-bottom: 10px;z-index: 100;">
              <novice-boot
                NoviceKey="businessBatchExecute"
                :NoviceArr="[{title: '', text: $t('business.executeHelp')}]"
                @updateGuidanceSuccess="updateGuidanceSuccess"
              ></novice-boot>
            </div>
          </div>
        </template>
        <template slot="batchExecutePopover" slot-scope="slotProps">
          <el-popover
            ref="popover"
            placement="top"
            width="120"
            trigger="manual"
            popper-class="padding-no-tooltip"
            v-model="batchBusiness.show"
            :disabled="slotProps.item.enabled"
            >
            <p class="batch-step"
               v-for="item in batchBusiness.operateSelect"
               @click.stop="showTaskAction(item.value)"
            >{{item.label}}</p>
            <p class="batch-step pink" @click.stop="showTaskBack('back')">{{$t('business.return')}}</p>
            <el-tooltip slot="reference" effect="dark" :disabled="!slotProps.item.enabled" :content="slotProps.item.tooltipContent" placement="top-start">
              <span class="option" @click="batchExecute(slotProps.item.action, slotProps.item.enabled)" :class="!slotProps.item.enabled ? '': 'disabled'">
                <i :class="slotProps.item.class"></i>{{$t(slotProps.item.name)}}
              </span>
            </el-tooltip>
          </el-popover>
        </template>
      </card-batch>
    </div>
   <custom-export :exportDialog="exportDialog" @export="exportExcel" :exportType="exportType"></custom-export>
    <!--批量分配工单组件-->
    <batch-assign ref="batchAssign" @batchAssignSuc="batchAssignSuc"></batch-assign>
    <!--批量执行工单组件-->
    <batch-execute ref="batchExecute" @batchExecuteSuc="batchExecuteSuc"></batch-execute>
  </div>
  <div style='height:100%' v-else>
    <keep-alive>
      <router-view>
      </router-view>
    </keep-alive>
 </div>
</div>
</template>
<script>
  const normalForm = {query: '', page: 1, morePage: 1, limit: 10}
  const businessAll = {status: null, createUser: null, ownercomCreateUser: null, ownerdepCreateUser: null, query: null, flow: [], step: null, processTimeout: '', processMember: null, ownercomProcessMember:null,ownerdepProcessMember:null,customField:null,textFieldContent:null,master: null, ownercom: null, ownerdep: null, number: null, createTime: null, priority: null, followedAgents: '', processEndTime: null, searchType: '', custom: {}, stepHistory: null}
  import BusinessTable from './BusinessTable.vue'
  import Select from '@/components/public-modules/card/search/Select'
  import InputSearch from '@/components/public-modules/card/search/InputSearch'
  import AdvancedSearch from '@/components/public-modules/card/search/Advanced2Search'
  import {isHasFunc, utilExtend, deepClone, getDateTime, removeEmptyProperty, getFormatDateTime, timeFormat, getCache} from '@/utils/m7Utils'
  import {getFlowAction, getFlowStepActionById, getTextFieldsNameByCache,getStepRoles,getStepQueues, getQueueAgents,  getRoleAgents, arrayContainsStr, sortBusinessFields, advancedSearchBack, getFlowStepNameByCache, getStartStep, getFlowStepById, createFlowCustomFields, addBusienssSelectCascade} from '@/utils/workflowUtils'
  import Pagination from '@/components/public-modules/card/Pagination'
  import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge'
  import CardBatch from '@/components/public-modules/card/CardBatch'
  import noviceBoot from '@/components/public-modules/novice-boot/index.vue'
  import * as uuid from 'uuid'
  import * as gtypes from '@/store/mutation-types'
  import BatchAssign from './BatchAssign'
  import BatchExecute from './BatchExecute'
  import CustomExport from './customExport.vue'
  export default {
    name: 'SideBarBusiness',
    data () {
      let timeoutData = [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.totalTimeStateUncomplete2'), value: true}, {label: this.$t('business.noTimeout'), value: false}]
      let attachmentData = [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.attachment'), value: true}, {label: this.$t('business.noAttachment'), value: false}]
      let priorityData = [{label: this.$t('business.priority1'), value: '1__' + this.$t('business.priority1')}, {label: this.$t('business.priority2'), value: '2__!' + this.$t('business.priority2'), class: 'business-priority2'}, {label: this.$t('business.priority3'), value: '3__!!!' + this.$t('business.priority3'), class: 'business-priority3'}]
      //工单创建方式数据
      let createModeData = [{label: this.$t('business.sessionCreate'), value: 'webchat__' + this.$t('business.sessionCreate')}, {label: this.$t('business.callsCreate'), value: 'call__' + this.$t('business.callsCreate')}, {label: this.$t('business.businessCreation'), value: 'business__' + this.$t('business.businessCreation')}, {label: this.$t('business.interfaceCreate'), value: 'interface__' + this.$t('business.interfaceCreate')}, {label: this.$t('business.customerCreate'), value:'customer__' + this.$t('business.customerCreate')}, {label: this.$t('business.mailCreate'), value: 'email__' + this.$t('business.mailCreate')}]
      return {
        pages: 0,  //  pageMore  翻页优化相关
        isSelectClick: false,
        noChange: false,
        activeName: 'business_undeal',
        type: 'business',
        isNotify: false,
        isAdvSearchClick: false,
        search: {
          // isAdvSearch: false,
          isSearch: false, // 是否正在执行搜索
          advSearchCondition: {}, // 高级搜索的查询条件展示
          placeHolder: this.$t('business.queryPlaceHolding'),
          business_undeal: {
            currentSelect: {value: undefined, condition: {}},
            isAdvSearch: false,
            partakeAgentRemark: false,
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            condition: {},
            isChildren: {
              rel: false,
              refresh: true,
              select: [
              ],
              defaultSelect: '',
              nomal: true,
              nomalForm: deepClone(normalForm),
              adv: {
                form: {createUser: null, ownercomCreateUser: null, ownerdepCreateUser: null, flow: [], step: null, processTimeout: '', processMember: null,ownercomProcessMember:null,ownerdepProcessMember:null,customField:null,textFieldContent:null, number: null, createTime: null, priority: null, followedAgents: '', searchType: '', custom: {}, stepHistory: null},
                advSearchOptions: {
                  localed: [
                    {label: this.$t('business.searchScope'), name: 'searchType', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.myFollowedBusiness'), value: 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')}]},
                    {label: this.$t('public.creator'), name: 'createUser', inputType: 'owner'},
                    {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
                    {label: this.$t('business.businessFlow'), filterable: true, name: 'flow', inputType: 'select', data: [], multiple: true},
                    {label: this.$t('business.businessStep'), name: 'step', inputType: 'select', data: [],multiple: true},
                    {label: this.$t('business.businessNumber'), name: 'number', inputType: 'input', validateType: 'Number3'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'owner'},
                    {label: this.$t('business.workOrderFuzzySearchField'), name: 'customField', inputType: 'select', data: []},
                    {label: this.$t('business.fuzzySearchContent'), name: 'textFieldContent', inputType: 'input',disabled:true},
                    {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
                    {label: this.$t('business.priorityLabel'), name: 'priority', inputType: 'select', data: priorityData, multiple: true},
                    {label: this.$t('business.businessAttachment'), name: 'existAttach', inputType: 'select', data: attachmentData},
                    {label: this.$t('business.businessCreationMode'), name: 'createMode', inputType: 'select', multiple: true, data: createModeData},
                    {label: this.$t('business.businessHistoryStep'), name: 'stepHistory', inputType: 'select', data: [],multiple: true}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          },
          business_my: {
            currentSelect: {value: undefined, condition: {}},
            isAdvSearch: false,
            partakeAgentRemark: false,
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            condition: {},
            isChildren: {
              rel: false,
              refresh: true,
              select: [
              ],
              defaultSelect: '',
              nomal: true,
              nomalForm: deepClone(normalForm),
              adv: {
                form: {createUser: null, ownercomCreateUser: null, ownerdepCreateUser: null, query: null, flow: [], step: null, processTimeout: '', processMember: null,ownercomProcessMember:null,ownerdepProcessMember:null,customField:null,textFieldContent:null, number: null, createTime: null, priority: null, followedAgents: '', searchType: '', custom: {}, stepHistory: null},
                advSearchOptions: {
                  localed: [
                    {label: this.$t('business.searchScope'), name: 'searchType', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.myFollowedBusiness'), value: 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')}, {label: this.$t('business.myTemp'), value: 'temp__' + this.$t('business.myTemp')}]},
                    {label: this.$t('public.creator'), name: 'createUser', inputType: 'owner'},
                    {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
                    {label: this.$t('business.businessFlow'), filterable: true, name: 'flow', inputType: 'select', data: [], multiple: true},
                    {label: this.$t('business.businessStep'), name: 'step', inputType: 'select', data: [],multiple: true},
                    {label: this.$t('business.businessNumber'), name: 'number', inputType: 'input'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('business.priorityLabel'), name: 'priority', inputType: 'select', data: priorityData, multiple: true},
                    {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'owner'},
                    {label: this.$t('business.workOrderFuzzySearchField'), name: 'customField', inputType: 'select', data: []},
                    {label: this.$t('business.fuzzySearchContent'), name: 'textFieldContent', inputType: 'input',disabled:true},
                    {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
                    {label: this.$t('business.businessAttachment'), name: 'existAttach', inputType: 'select', data: attachmentData},
                    {label: this.$t('business.businessCreationMode'), name: 'createMode', inputType: 'select', multiple: true, data: createModeData},
                    {label: this.$t('business.businessHistoryStep'), name: 'stepHistory', inputType: 'select', data: [],multiple: true}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          },
          business_all: {
            currentSelect: {value: undefined, condition: {}},
            isAdvSearch: false,
            partakeAgentRemark: false,
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            condition: {},
            isChildren: {
              rel: true,
              refresh: true,
              quickSelectDefault: 'time__week',
              select: [],
              defaultSelect: 'time__week',
              nomal: true,
              nomalForm: deepClone(normalForm),
              adv: {
                form: deepClone(businessAll),
                advSearchOptions: {
                  localed: [
                    {label: this.$t('business.searchScope'), name: 'searchType', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.myFollowedBusiness'), value: 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')}, {label: this.$t('business.myParticipated'), value: 'myParticipated__' + this.$t('business.myParticipated')}, {label: this.$t('business.myTemp'), value: 'temp__' + this.$t('business.myTemp')}]},
                    {label: this.$t('business.businessStatus'), name: 'status', inputType: 'select', data: [{label: this.$t('business.undeal'), value: 'dealing__' + this.$t('business.undeal')}, {label: this.$t('business.todo'), value: 'dealing__' + this.$t('business.todo')}, {label: this.$t('business.finished'), value: 'complete__' + this.$t('business.finished')}, {label: this.$t('public.cancel'), value: 'cancel__' + this.$t('public.cancel')}],multiple: true},
                    {label: this.$t('public.creator'), name: 'createUser', inputType: 'owner'},
                    {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
                    {label: this.$t('business.businessFlow'), filterable: true, name: 'flow', inputType: 'select', data: [], multiple: true},
                    {label: this.$t('business.businessStep'), name: 'step', inputType: 'select', data: [],multiple: true},
                    {label: this.$t('business.master'), name: 'master', inputType: 'owner'},
                    {label: this.$t('business.businessNumber'), name: 'number', inputType: 'input'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('business.processEndTime'), name: 'processEndTime', inputType: 'time'},
                    {label: this.$t('business.priorityLabel'), name: 'priority', inputType: 'select', data: priorityData, multiple: true},
                    {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'owner'},
                    {label: this.$t('business.workOrderFuzzySearchField'), name: 'customField', inputType: 'select', data: []},
                    {label: this.$t('business.fuzzySearchContent'), name: 'textFieldContent', inputType: 'input',disabled:true},
                    {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
                    {label: this.$t('business.businessAttachment'), name: 'existAttach', inputType: 'select', data: attachmentData},
                    {label: this.$t('business.businessCreationMode'), name: 'createMode', inputType: 'select', multiple: true, data: createModeData},
                    {label: this.$t('business.businessHistoryStep'), name: 'stepHistory', inputType: 'select', data: [],multiple: true}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          }
        },
        formItemsConfigs: {},
        pagination: {
          currentPage: 0,
          count: 0,
          totalPage: 0
        },
        form: {
          type: 'add',
          data: {}
        },
        searchObj: {
          page: 1,
          limit: 10
        },
        tableHeader: [
          {prop: 'name', label: '工单标识'},
          {prop: 'cascade', label: '工单编号'},
          {prop: 'userName', label: '关联客户'},
          {prop: 'priority', label: '工单优先级'},
          {prop: 'businessType', label: '工单类型'},
          {prop: 'businessStep', label: '当前步骤'},
          {prop: 'agentAfter', label: '当前处理人'},
          {prop: 'agentBefore', label: '创建人'},
          {prop: 'createTime', label: '创建时间'},
          {prop: 'operation', label: '操作', opera: []}
        ],
        tableData: [],
        sessionId: this.$store.state.session.sessionId,
        pagination: {
          count: 0,
          allCount: 0,
          moreFlag: true,
          currentPage: 1
        },
        queryObj: {},
        qu: {},
        batch: {
          batchItem: [],
          allChecked: false,
          isBatchShow: false,
          checkedCount: 0,
          operator: [
            {
              "name": "public.delete",
              "class": "iconfont icon-shanchu",
              "action": "deleteTip"
            },
            {
              "name": "public.export",
              "class": "icon-daochu1 iconfont",
              "action": "exportExcel"
            },
            {
              "name": "business.batchReceive",
              "class": "icon-pilianglingqu iconfont",
              "action": "batchReceive"
            },
            {
              "name": "business.batchAssign",
              "class": "icon-fenpei iconfont",
              "action": "batchAssign",
              "tooltipContent": "请您先筛选出某一工单类型及工单步骤下的工单列表后，再来进行批量分配。",
              "enabled": true
            }
          ],
          // 公共批处理
          operatorCommon: [
          ],
          // 待领取tab下批处理
          operatorUndeal: [
            {name: 'business.batchReceive', class: 'icon-pilianglingqu', action: 'batchReceive'}
          ],
          // 我的代办tab下批处理
          operatorMy: [
            { name: 'business.batchExecute',
              class: 'icon-piliangchuli',
              action: 'batchExecute',
              tooltipContent: this.$t('business.executeSearchTip'),
              enabled: true, // 是否禁用
              popover: 'batchExecutePopover'
            }
          ]
        },
        getNoviceKeyStatus: {'businessBatchAssign': false, 'businessBatchExecute': false},
        batchBusiness: {
          show: false,
          operateSelect: [], // 步骤动作
          argu: {} // 数量，条件参数
        },
        exportDialog: {
          isShow: false,
          type: 'export',
          headers: [
            {name: this.$t('business.businessNumber'), value: 'number', default: true},
            {name: this.$t('business.customerName'), value: 'name', default: true},
            {name: this.$t('business.phone'), value: 'phone', default: true},
            {name: this.$t('business.priorityLabel'), value: 'priority', default: true},
            {name: this.$t('business.businessFlow'), value: 'flow', default: true},
            {name: this.$t('business.businessStep'), value: 'step', default: true},
            {name: this.$t('business.lastStep'), value: 'lastStep', default: false, prompt: this.$t('business.lastStepTip')},
            {name: this.$t('business.businessStatus'), value: 'status', default: true},
            {name: this.$t('business.master'), value: 'master', default: true},
            {name: this.$t('business.callNum'), value: 'callId', default: true},
            {name: this.$t('call.callNumber'), value: 'CALL_SHEET_ID', default: false},
            {name: this.$t('webchat.exportHead.sessionID'), value: 'webChatId', default: false},
            {name: this.$t('business.chatSatisfaction'), value: 'webChatCsr', default: false},
            {name: this.$t('business.customFields'), value: 'customFields', default: true},
            {name: this.$t('business.backInfo'), value: 'backInfo', default: true},
            {name: this.$t('business.createTime'), value: 'createTime', default: false},
            {name: this.$t('business.firstCreateTime'), value: 'firstCreateTime', default: false},
            {name: this.$t('business.creator'), value: 'creator', default: false},
            {name: this.$t('business.receiveTimes'), value: 'receiveTimes', default: false},
            {name: this.$t('business.stepsTime'), value: 'stepsInfo', default: false},
            {name: this.$t('business.circulationPath'), value: 'circulationPath', default: false},
            {name: this.$t('business.processEndTime'), value: 'processEndTime', default: false},
            {name: this.$t('business.callAppraise'), value: 'callAppraise', default: false},
            {name: this.$t('business.businessAppraise'), value: 'businessAppraise', default: false},
            {name: this.$t('business.allCustomer'), value: 'customer', default: false},
            {name: this.$t('business.businessCreationMode'), value: 'createMode', default: false},
            {name: this.$t('webchat.relationBusiness'), value: 'relatedBusiness', default: false},
          ],
          select: [],
          downloadAgents: [],
          agents: [],
          fileType: 'csv'
        },
        exportType: this.$store.state.isRealTimeExport ? 'real' : '', // real实时导出任务
        selectLength: 0,
        laterProcessData: []
      }
    },
    components: {
      BusinessTable,
      InputSearch,
      AdvancedSearch,
      'v-select': Select,
      Pagination,
      AdvSchBadge,
      CardBatch,
      noviceBoot,
      BatchAssign,
      BatchExecute,
      CustomExport
    },
    mounted () {
      document.addEventListener('click', this.listenerFun)
    },
    beforeDestroy () {
      document.removeEventListener('click', this.listenerFun)
    },
    methods: {
      selectAll (data) {
        if (data) {
          this.$refs.businessTable.checkAll()
        } else {
          this.$refs.businessTable.clearSelection()
        }
      },
      close () {
        this.$refs.CustomSearchDialog.handleClose()
      },
      addSearch () {
        this.form.type = 'add'
        this.$refs.CustomSearchDialog.open()
      },
      operate (event) {
        let type = event.type
        if (type === 'setTask') {
          this.businessRefresh()
          this.refreshUndealNum()
        }
      },
      deleteQuestion (data) {
        this.$confirm(this.$t('business.businessDeleteTip'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        })
          .then(() => {
            this.$store.dispatch('removeQuickSearch', data)
              .then(resp => {
                if (resp.success) {
                  this._search()
                  this.$store.commit('business/CUSTOM_SEARCH')
                  this.$message({
                    type: 'success',
                    message: this.$t('message.deleteSucc')
                  })
                }
              })
          })
      },
      saveForm (data) {
        if (this.form.type === 'add') {
          this.$store.dispatch('addQuickSearch', data).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('config.channel.saveSuccess'))
              this._search()
              this.$store.commit('business/CUSTOM_SEARCH')
              this.close()
            }
          })
        } else if (this.form.type === 'edit') {
          data._id = this.form.data._id
          this.$store.dispatch('updateQuickSearch', data).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('business.updateSuccess'))
              this.close()
              this._search()
              this.$store.commit('business/CUSTOM_SEARCH')
            }
          })
        }
      },
      setDefault (data) {
        this.$store.dispatch('updateQuickSearch', {_id: data._id, menu: data.menu, default: data.default === 'true' ? 'false' : 'true'}).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('config.channel.configSuccess'))
            this._search()
            this.$store.commit('business/CUSTOM_SEARCH')
          }
        })
      },
      _search (page) {
        this.searchObj.page = typeof page === 'number' ? page : 1
        this.$store.dispatch('queryQuickSearchList', this.searchObj).then((res) => {
          if (res.success) {
            this.pagination.count = res.count
            this.pagination.currentPage = this.searchObj.page
            let list = res.data || []
            for (let i = 0; i < list.length; i++) {
              let one = list[i]
              let agent = this.$agentsMap() || {}
              let createUserName = agent[one.createUser]
              let menuName = ''
              if (createUserName) {
                createUserName = createUserName.displayName
              } else {
                createUserName = '-'
              }
              one.createUserName = createUserName
              if (one.menu === 'all') {
                menuName = this.$t('public.all')
              } else if (one.menu === 'undeal') {
                menuName = this.$t('business.undealBusiness')
              } else if (one.menu === 'my') {
                menuName = this.$t('business.myTodo')
              }
              one.menuName = menuName
              if (one.default === 'true') {
                one.operate = [{name: this.$t('public.edit'), type: 'edit'}, {name: this.$t('business.cancelDefaut'), type: 'default'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              } else {
                one.operate = [{name: this.$t('public.edit'), type: 'edit'}, {name: this.$t('business.addDefaut'), type: 'default'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]
              }
            }
            this.tableData = list
          }
        })
      },
      nomalSearch (value, pageNum) {
        if (value) {
          this.allCount = 0
          this.search[this.activeName].partakeAgentRemark = false
          this.search.isSearch = true
          let self = this
          self.loading = true

          this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
          this.search[this.activeName].isAdvSearch = false

          this.search[self.activeName].isChildren.nomalForm.query = value
          let queryData = deepClone(this.search[self.activeName].isChildren.nomalForm)
          Object.assign(queryData, this.search[this.activeName].currentSelect.condition)
          queryData.page = pageNum || 1
          self.search[self.activeName].pagination.currentPage = pageNum || 1
          let morePage = 1
          morePage = queryData.page === 1 ? 1 : Math.floor(pageNum / this.pages + 1)
          queryData.morePage = morePage || 1
          let queryData1 = deepClone(this.$store.state.business.getBusinessFirstQuery)
          queryData1.query = value
          this.getBusiness(this.$store, self.activeName, queryData1)
          // this.getBusiness(this.$store, this.activeName, queryData)
        } else {
          let firstQuery = this.$store.state.business.getBusinessFirstQuery
          this.$store.commit('business/GET_BUSINESS_QUERY', firstQuery)
        }
      },
      selectShow () {
        if (this.activeName === 'business_my') {
          // 查询暂存工单和稍后处理工单数量
          let master = this.$store.state.session.sessionId
          let temp = this.$store.dispatch('queryAllBusinessCount', {queryCount: true, master, saveFlag: 'temp'})
          let laterProcess = this.$store.dispatch('queryAllBusinessCount', {queryCount: true, master, laterProcess: true})
          Promise.all([temp, laterProcess]).then(([tempNum, laterNum]) => {
            this.search.business_my.isChildren.select[1].label = this.$t('business.laterProcess') + `(${laterNum.count > 99 ? 99 + '+' : laterNum.count})`
            this.search.business_my.isChildren.select[2].label = this.$t('business.myTemp') + `(${tempNum.count > 99 ? 99 + '+' : tempNum.count})`
          })
        }
      },
      businessAdd () {
        this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: true})
        let path = '/index/business/newBusiness'
        this.$router.push({path: path})
      },
      getBusinessList (data) {
        this.$store.commit('business/SET_BUSINESS_SHOW_LOADING', true)
        let action = 'queryAllBusiness'
        this.$store.dispatch(action, data).then((res) => {
          if (res && res.success) {
            if (data.page === 1 && res.count) {
              this.pages = res.count / 10
            }
            this.$set(this.pagination, 'moreFlag', res.more)
            this.$set(this.pagination, 'count', res.count)
            this.$set(this.pagination, 'allCount', res.count)
            if (res.list.length === 0) {
              this.$set(this, 'tableData', [])
            } else {
              this.$set(this, 'tableData', res.list)
            }
            this.$store.commit('business/SET_BUSINESS_SHOW_LOADING', false)
            if (this.isNotify) {
              let list = this.$store.state[this.type][this.type + 'List'].list || []
              if (list.length) {
                let data = list[0]
                this.$store.commit('business/OPERATION_NEW_BUSINESS_SLIDE', { active: 'business_all', flag: 'selectSide'})
                this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: true})
                this.$router.push('/index/business/business_all/' + data._id + '/' + (data.customer || 'no-customer-bus'))
                this.$store.commit('business/REFRESH_BUS_RIGHT', Math.random())
              }
            }
            this.isNotify = false
            // 判定是否是获取真实的count,如果是获取的是真实的count，则不进行处理
            if (!data.queryCount) {
              // 如果返回的列表不为空，则直接保留在当前页，不做任何处理
              // 如果返回的列表为空，则有两种情况，如果有多于 则返回到第一页，否则返回到最后一页
              if (res.list.length === 0) {
                this.laterProcessData = []
                if (res.more) {
                  this.turnPage(1)
                } else {
                  // 算出最后一页的页数
                  let page = Math.ceil(res.count / 10)
                  if (res.count === 0) {
                    // 第一页且count为0是不再发请求
                    this.pagination.currentPage = 1
                  } else {
                    this.turnPage(page)
                  }
                }
              }else{
                if(data.laterProcess){
                  let maxPage = Math.ceil(res.count / 10)
                  if (this.pagination.currentPage > maxPage) {
                    this.pagination.currentPage = maxPage
                  }
                  let page = this.pagination.currentPage
                  this.turnPage(page,true)
                }else{
                  this.laterProcessData = []
                }
              }
            }
          }
          return Promise.resolve()
        })
      },
      businessType (item) {
        let businessFlows = this.$getCache('businessFlow') || []
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === item.flow) {
            let {name, showFields, fields} = businessFlows[i]
            let step = getStartStep(businessFlows[i])
            let stepFields = step.stepFields || []
            let detail = [{name: this.$t('business.businessNumber'), value: item.number}]
            let summary = []
            sortBusinessFields(stepFields, fields, item, detail, 'card')
            if (showFields && showFields.length) {
              detail.forEach((item) => {
                if (showFields.indexOf(item._id) !== -1 && item.value) {
                  summary.push(item.value)
                }
              })
            }
            return {name, detail, summary}
          }
        }
        try {
          const data = {
            env: {
              browser: {name: 'Chrome', version: '67.0.3396.99'},
              os: 'Mac',
              userAgent: 'Mozilla/5.0'
            },
            extra: {
              componentName: '工单卡片'
            },
            errorType: 'TypeError',
            message: '工单卡片',
            referrer: 'http://kf.com/customer',
            stacktrace: {
              frames: []
            },
            trimHeadFrames: 1,
            url: '',
            exception: {
              values: [{
                type: 'TypeError',
                value: '错误信息：工单卡片信息item.flow：' +
                (item.flow || '') +
                '   item.number：' + item.number + '工单类型flows长度：' + businessFlows.length,
                stacktrace: {
                  frames: []
                }
              }]
            }
          }
          let req = {
            data,
            action: 'app.collect.collectVueErrorInfo'
          }
          http.fetch(req, 'post')
            .then((res) => {
            })
            .catch(err => {
              console.error(err)
            })
        } catch (err) {
          console.log(err)
        }

        return {name: '', detail: [], summary: []}
      },
      businessStep (flowId, status, step) {
        let businessStep = {name: '', type: ''}
        let businessFlows = this.$getCache('businessFlow')
        if (!businessFlows) {
          return businessStep
        }
        let flow = null
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === flowId) {
            flow = businessFlows[i]
            break
          }
        }
        if (status !== 'complete' && status !== 'cancel') {
          businessStep.type = 'b-step'
        } else {
          businessStep.type = 'finish'
        }
        let steps = flow ? flow.steps : []
        for (let i = 0; i < steps.length; i++) {
          var stepsItem = steps[i]
          if (stepsItem._id === step) {
            businessStep.name = stepsItem.name
            break
          }
        }
        return businessStep
      },
      agentAfter (master) {
        if (master === '') {
          return ''
        } else {
          let agent = this.$agentsMap() || {}
          return agent[master] ? agent[master].displayName : ''
        }
      },
      agentBefore (createUser) {
        let agent = this.$agentsMap() || {}
        return agent[createUser] ? agent[createUser].displayName : ''
      },
      name (item) {
        let name = ''
        let className = ''
        if (!item.customer) {
          name = this.$t('customer.customerSlot.unlocation')
          className = 'unknowCus'
        } else if (!item.name) {
          name = this.$t('business.hasRemoveCus')
          className = 'deleteCus'
        } else {
          name = item.name
        }
        return {className, name}
      },
      turnPage (value,flag) {
        if(flag){
          this.pagination.currentPage = value || 1
          let size = 10
          let end = Math.min(size * (value), this.$store.state[this.type][this.type + 'List'].count)
          this.laterProcessData = this.$store.state[this.type][this.type + 'List'].list.slice(size * (value - 1), end)
        }else{
          this.pagination.currentPage = value
          this.queryObj.page = value
          let morePage = value >= this.pages ? Math.floor(value / this.pages + 1) : 1
          this.queryObj.morePage = morePage || 1
          this.getBusinessList(this.queryObj)
        }
      },
      handlerSelectChange (selectObj) {
        let selectName = selectObj.selectName
        let selectValue = selectObj.selectValue
        let custom = selectObj.custom
        let cascadeIndex = selectObj.cascadeIndex
        if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'createUser') {
          this.search[this.activeName].isChildren.adv.form.ownercomCreateUser = null
          this.search[this.activeName].isChildren.adv.form.createUser = null
          this.search[this.activeName].isChildren.adv.form.ownerdepCreateUser = null
          if (selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.createUser = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName + 'CreateUser'] = selectValue
          }
        }
        if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'processMember') {
          this.search[this.activeName].isChildren.adv.form.ownercomProcessMember = null
          this.search[this.activeName].isChildren.adv.form.processMember = null
          this.search[this.activeName].isChildren.adv.form.ownerdepProcessMember = null
          if (selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.processMember = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName + 'ProcessMember'] = selectValue
          }
        }
        if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'master') {
          this.search[this.activeName].isChildren.adv.form.ownercom = null
          this.search[this.activeName].isChildren.adv.form.master = null
          this.search[this.activeName].isChildren.adv.form.ownerdep = null
          if (selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.master = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName] = selectValue
          }
        }
        // 工单类型改变
        if (selectName === 'flow') {
          if (selectValue.length !== 1 || selectValue.length === 0) {
            this.search[this.activeName].isChildren.adv.advSearchOptions.custom = []
            this.search[this.activeName].isChildren.adv.form.custom = {}
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'step') {
                this.search[this.activeName].isChildren.adv.form.step = null
                item.data = []
              }
              if (item.name === 'stepHistory') {
                this.search[this.activeName].isChildren.adv.form.stepHistory = null
                item.data = []
              }
              if (item.name === 'customField') {
                this.search[this.activeName].isChildren.adv.form.customField = null
                item.data = []
              }
              if (item.name === 'textFieldContent') {
                this.search[this.activeName].isChildren.adv.form.textFieldContent = null
                item.disabled = true
              }
            })
            return
          }
          getBusinessFlowStep(this.$store, selectValue.toString()).then((flow) => {
            let steps = flow.steps || []
            let stepsSelectData = []
            let Fields = flow.fields || []
            let FieldsSelectData = [{label: this.$t('public.all'), value: ''}]
            for (let i = 0; i < steps.length; i++) {
              let stepsItem = steps[i]
              stepsSelectData.push({label: stepsItem.name, value: stepsItem._id})
            }
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'step') {
                this.search[this.activeName].isChildren.adv.form.step = null
                item.data = stepsSelectData
              }
              if (item.name === 'stepHistory') {
                this.search[this.activeName].isChildren.adv.form.stepHistory = null
                item.data = stepsSelectData
              }
            })
            for (let i = 0; i < Fields.length; i++) {
              let FieldsItem = Fields[i]
              if(FieldsItem.type=='single'||FieldsItem.type=='multi'){
                FieldsSelectData.push({label: FieldsItem.name, value: FieldsItem._id})
              }
            }
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'customField') {
                this.search[this.activeName].isChildren.adv.form.customField = null
                item.data = FieldsSelectData
              }
            })
            let startStep = getStartStep(flow)
            let step = getFlowStepById(flow, startStep._id)
            let fields = step ? step.stepFields : []
            let flowFields = flow ? flow.fields : []
            let customFormFields = createFlowCustomFields(fields, flowFields, true)
            // let newFieldsArr = []
            // if (customFormFields.advFields) {
            //   customFormFields.advFields.forEach((item) => { // 去掉客户自定义字段中日期
            //     if (item.inputType !== 'time' && item.inputType !== 'datetime' && item.inputType !== 'date') {
            //       newFieldsArr.push(item)
            //     }
            //   })
            // }
            this.search[this.activeName].isChildren.adv.advSearchOptions.custom = customFormFields.advFields || []
            this.search[this.activeName].isChildren.adv.form.custom = customFormFields.customForm
          })
        }
        if(selectName === 'status'){
          if(selectValue.length>0){
            let nameArr =[]
            selectValue.map(val=>{
              nameArr.push(val.split('__')[1])
            })
            //待办和待领取特殊处理，但同时存在masterStatus为''，待领取''.待办null
            let count = 0
            if(nameArr.indexOf(this.$t('business.todo'))!==-1){
              count++
            }
            if(nameArr.indexOf(this.$t('business.undeal'))!==-1){
              count++
            }
            if(count>1){
              this.search[this.activeName].isChildren.adv.form.master = ''
              this.search[this.activeName].isChildren.adv.form.masterStatus=''
            } else{
              if(nameArr.includes(this.$t('business.todo'))){
                this.search[this.activeName].isChildren.adv.form.master = null
                this.search[this.activeName].isChildren.adv.form.masterStatus=null
              }
              if(nameArr.includes(this.$t('business.undeal'))) {
                this.search[this.activeName].isChildren.adv.form.masterStatus = ''
              }
            }
            // selectValue.forEach(item=>{
            //   if(item.split('__')[1]== this.$t('business.todo')){
            //       this.search[this.activeName].isChildren.adv.form.master=null
            //   }
            // })
          }
        }
        if(selectName === 'customField'){
          this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
            if (item.name === 'textFieldContent') {
              this.search[this.activeName].isChildren.adv.form.textFieldContent = null
              item.disabled = false
            }
          })
        }else{
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
            if (item.name === 'textFieldContent') {
              this.search[this.activeName].isChildren.adv.form.textFieldContent = null
              item.disabled = true
            }
          })
        }
        // 自定义字段的级联
        if (custom) {
          let fieldId = selectName.split('_')[0]
          let rootValue = this.search[this.activeName].isChildren.adv.form.custom[fieldId]
          addBusienssSelectCascade(this.$store, selectValue, fieldId, cascadeIndex, rootValue).then((labels, cascade) => {
            this.search[this.activeName].isChildren.adv.advSearchOptions.custom.forEach((item) => {
              // let selectName = fieldId + '_' + (cascadeIndex + 1)
              let currentField = item.name.split('_')
              if (currentField[0] === fieldId) {
                // 当前select后面的下拉框重置
                if (currentField[1] > cascadeIndex + 1) {
                  this.search[this.activeName].isChildren.adv.form.custom[item.name] = null
                  item.data = []
                } else if (currentField[1] === (cascadeIndex + 1).toString()) {
                  this.search[this.activeName].isChildren.adv.form.custom[item.name] = null
                  item.data = labels
                }
              }
            })
          })
        }
      },
      advSearch (clearBadge, pageNum, emitData) {
        this.$store.commit('business/OPERATION_NEW_BUSINESS_SLIDE', { active: this.activeName, flag: 'selectSide'})
        window._hmt && window._hmt.push(['_trackEvent', '其他统计', this.activeName + ' 高级搜索'])
        this.allCount = 0
//        let selectName = ''
//        if (emitData && emitData.selectName) {
//          selectName = emitData.selectName ? emitData.selectName : ''
//        }
        // this.noChange = true
//        if (selectName === 'flow') {
//          this.search[this.activeName].isChildren.nomalForm.value = ''
//        }
        this.search[this.activeName].currentSelect.value = ''
        this.search[this.activeName].currentSelect.condition = {}
        this.search.isSearch = true
        let self = this
        self.loading = true
        let form = this.search[this.activeName].isChildren.adv.form
        if(this.activeName=='business_all'&&form.status){
          form.status.forEach(item=>{
            if(item.split('__')[1]== this.$t('business.undeal')){
                form.master = ''
            }
          })
        }
        let tempArr = {}
        // 全部tab下工单编号为空时，创建时间必填
        if (this.activeName === 'business_all' && !form.number && (!form.createTime)) {
          this.defaultSetting()
        }
        // deepClone后createtiem里日期消失
        if (form.createTime && form.createTime[0] !== null) {
          form.createTime$begin = getDateTime(form.createTime[0])
        } else {
          form.createTime$begin = ''
        }
        if (form.createTime && form.createTime[1] !== null) {
          form.createTime$end = getDateTime(form.createTime[1])
        } else {
          form.createTime$end = ''
        }
        if (form.processEndTime && form.processEndTime[0] !== null) {
          form.processEndTime$begin = getDateTime(form.processEndTime[0])
        } else {
          form.processEndTime$begin = ''
        }
        if (form.processEndTime && form.processEndTime[1] !== null) {
          form.processEndTime$end = getDateTime(form.processEndTime[1])
        } else {
          form.processEndTime$end = ''
        }
        for (let m in form.custom) {
          if (form.custom[m] instanceof Date) {
            form.custom[m] = getDateTime(form.custom[m])
          }
        }
        let searchQuery = deepClone(form)
        let flows = this.$store.state.business.transCache.businessTypes
        if (clearBadge === true) {
          self.search[this.activeName].isAdvSearch = false
          // 清空高级搜索选项
          this.resetAdvSearch()
          searchQuery = {}
        } else {
          self.search[this.activeName].isAdvSearch = true
          let custom = searchQuery.custom
          delete searchQuery.createTime
          delete searchQuery.processEndTime
          for (let key in searchQuery) { // 搜索条件回显处理
            if ((searchQuery[key] || searchQuery[key] === false) && key !== 'custom') {
              tempArr[key] = searchQuery[key]
              if (key === 'flow') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                  for (let i = 0; i < flows.length; i++) {
                    if (flows[i].value === searchQuery[key][m]) {
                      name += flows[i].label + ' '
                      break
                    }
                  }
                }
                tempArr[key] = name
              }else if (key === 'priority') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                    name += searchQuery[key][m].split('__')[1] + ' '
                    if(searchQuery[key][m].split('__')[1]==this.$t('business.priority1')){
                      searchQuery[key][m]=searchQuery[key][m].split('__')[0]
                    }else if(searchQuery[key][m].split('__')[1]=='!'+this.$t('business.priority2')){
                      searchQuery[key][m]=searchQuery[key][m].split('__')[0]
                    }else{
                      searchQuery[key][m]=searchQuery[key][m].split('__')[0]
                    }
                }
                tempArr[key] = name
              }  else if (key === 'step') { 
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                  name += getFlowStepNameByCache(searchQuery.flow.toString(), searchQuery[key][m]) + ' '
                }
                tempArr[key] = name
              } else if (key === 'stepHistory') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                  name += getFlowStepNameByCache(searchQuery.flow.toString(), searchQuery[key][m]) + ' '
                }
                tempArr[key] = name
              }  else if (key === 'customField') {
                tempArr[key] = getTextFieldsNameByCache(searchQuery.flow.toString(), searchQuery.customField)
              }else if (key === 'status') {
                let statusArr = []
                tempArr[key] = []
                for (let m = 0; m < searchQuery[key].length; m++) {
                  if (searchQuery[key][m].indexOf('__')!==-1) {
                    tempArr[key] += searchQuery[key][m].split('__')[1] + ' '
                    statusArr.push(searchQuery[key][m].split('__')[0])
                  } else {
                    tempArr[key] += searchQuery[key][m]
                  }
                }
                searchQuery[key] = statusArr
              }else if (key === 'existAttach') {
                if (tempArr[key] === true) {
                  tempArr[key] = this.$t('business.attachment')
                } else if (tempArr[key] === false) {
                  tempArr[key] = this.$t('business.noAttachment')
                } else {
                  tempArr[key] = ''
                }
              }else if (key === 'processTimeout') {
                if (tempArr[key] === true) {
                  tempArr[key] = this.$t('business.totalTimeStateUncomplete2')
                } else if (tempArr[key] === false) {
                  tempArr[key] = this.$t('business.noTimeout')
                } else {
                  tempArr[key] = ''
                }
              }else if (key === 'createMode') {
                let str = ''
                let arr = []
                searchQuery[key].forEach(item=>{
                  if (item.match(/__/)) {
                    str += item.substr(item.indexOf('__') + 2) + ' '
                    arr.push(item.substr(0, item.indexOf('__'))) 
                  } else {
                    str += item
                  }
                })
                tempArr[key] = str
                searchQuery[key] = arr
              } else if (searchQuery[key] && typeof searchQuery[key] === 'string') {
                if (searchQuery[key].match(/__/)) {
                  tempArr[key] = searchQuery[key].substr(searchQuery[key].indexOf('__') + 2)
                  searchQuery[key] = searchQuery[key].substr(0, searchQuery[key].indexOf('__'))
                } else {
                  tempArr[key] = searchQuery[key]
                }
              }
            }
          }
          for (let i in custom) {
            searchQuery[i] = custom[i]
            // 处理time和date数据
            if (custom[i]) {
              this.search[this.activeName].isChildren.adv.advSearchOptions.custom.forEach((item) => {
                if (item.name === i && item.inputType === 'time') {
                  searchQuery[i] = custom[i].split(' ')[1]
                } else if (item.name === i && item.inputType === 'date') {
                  searchQuery[i] = custom[i].split(' ')[0]
                }
              })
            }
          }
          // 自定义字段回显
          tempArr = Object.assign(tempArr, advancedSearchBack(custom))
          delete searchQuery.custom
        }
        // 我参与的工单提示
        if (!searchQuery.processMember) {
          this.search[this.activeName].partakeAgentRemark = false
        } else {
          this.search[this.activeName].partakeAgentRemark = true
        }
        // 部门组件处理
        if (searchQuery.ownercom === 'all') {
          searchQuery.ownercom = ''
        }
        if (searchQuery.ownercomCreateUser === 'all') {
          searchQuery.ownercomCreateUser = ''
        }
        if (searchQuery.ownercomProcessMember === 'all') {
          searchQuery.ownercomProcessMember = ''
        }
        this.search[this.activeName].isChildren.adv.badgeList = removeEmptyProperty(tempArr)
        searchQuery.page = pageNum || 1
        let morePage = 1
        morePage = searchQuery.page === 1 ? 1 : Math.floor(pageNum / this.pages + 1)
        searchQuery.morePage = morePage || 1
        self.search[self.activeName].pagination.currentPage = pageNum || 1
        self.search[self.activeName].condition = searchQuery
        self.isAdvSearchClick = true
        if(searchQuery.customField&&searchQuery.textFieldContent){
          let obj = {}
          obj[searchQuery.customField] = searchQuery.textFieldContent
          searchQuery.customField=obj
        }else{
          searchQuery.customField=null
        }
        delete searchQuery.textFieldContent
        return this.getBusiness(this.$store, this.activeName, searchQuery)
      },
      resetAdvSearch () {
        let currentTab = this.search[this.activeName]
        currentTab.pagination.currentPage = 1
        this.noChange = false
        for (let key in currentTab.isChildren.adv.form) {
          if (key !== 'custom') {
            if (key === 'flow') {
              currentTab.isChildren.adv.form[key] = []
            } else {
              currentTab.isChildren.adv.form[key] = null
            }
          } else {
            currentTab.isChildren.adv.form[key] = {}
          }
        }
        this.search[this.activeName].isChildren.adv.advSearchOptions.custom = []
        this.search[this.activeName].isChildren.adv.advSearchOptions.localed.some((item) => {
           if (item.name === 'step') {
            item.data = []
            return false
          }
          if (item.name === 'customField') {
            item.data = []
            return false
          }
          if (item.name === 'textFieldContent') {
            item.disabled = true
            return false
          }
          if (item.name === 'stepHistory') {
            item.data = []
            return true
          }
        })
        if (this.activeName === 'business_all') {
          this.defaultSetting()
        }
      },
      handleConfirmNewItemsConfig ({data: formItemsConfig, done}) {
        var formItemsConfigs = deepClone(this.formItemsConfigs)
        formItemsConfigs[this.activeName] = formItemsConfig
        this.$store.dispatch('saveAdvSearchConfig', {
          searchType: 'BusinessCardGroup',
          config: formItemsConfigs
        }).then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
      },
      ifRemark (data) {
        // this.allCount = 0
        this.search[this.activeName].partakeAgentRemark = data
      },
      getBusiness (store, tabName, data) {
        this.allCount = 0
        let action = 'queryAllBusiness'
        let sessionId = this.$store.state.session.sessionId
        if (tabName === 'business_my') {
          data.flag = 'kf'
          data.menu = 'my'
          //快捷搜索为多选，这边默认加上的status和master数组处理
          if(data.type){
            data.status = ['dealing']
            data.master = [sessionId]
          }else{
            data.status = 'dealing'
            data.master = sessionId
          }
        } else if (tabName === 'business_all') {
          data.menu = 'all'
          data.flag = 'kf'
        } else {
          data.flag = 'kf'
          data.menu = 'undeal'
          data.master = ''  
          //快捷搜索为多选，这边默认加上的status数组处理，master默认空不处理
          if(data.type){
            data.status = ['dealing']
          }else{
            data.status = 'dealing'
          }
        }
        data.followedAgents = ''
        if (data.searchType === 'myFollowedBusiness') {
          data.followedAgents = sessionId
        } else if (data.searchType === 'temp') {
          data.saveFlag = 'temp'
          data.master = sessionId
        }
        // 如果工单参与人是我
        if (data.searchType === 'myParticipated') {
          data.myParticipated = true
//          delete data.menu
        }
        delete data.searchType
        let _qu = deepClone(data)
        _qu.queryCount = true
        this.qu = _qu
        this.quAction = action + 'Count'
        this.$store.commit('business/SET_BUSINESS_TYPE', tabName)
        this.$store.commit('business/GET_BUSINESS_QUERY', data)
        this.$store.commit('business/GET_FIRST_BUSINESS_QUERY', data)
        this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: false})
      },
      getAllCount () {
        this.allCount = 0
        let more = false
        this.$store.dispatch(this.quAction, this.qu).then((res) => {
          if (res.success) {
            this.allCount = res.count
            this.pagination.count = res.count
            this.pagination.moreFlag = false
            this.$store.commit('business/SET_BUSSINESS_MORE', {more})
          }
        })
      },
      refreshCustomSearch () {
        return this.$store.dispatch('queryQuickSearchListAll', {}).then((res) => {
          let obj = {}
          let all = [
            {label: this.$t('public.createTime'), value: 'none', disabled: true, condition: {}},
            {label: this.$t('webchat.today'), value: 'time__today', condition: {}},
            {label: this.$t('webchat.yesterday'), value: 'time__yesterday', condition: {}},
            {label: this.$t('webchat.lastWeek'), value: 'time__week', condition: {}},
            {label: this.$t('webchat.lastMonth'), value: 'time__month', condition: {}},
            {label: this.$t('webchat.oneYear'), value: 'time__oneYear', condition: {}},
            {label: this.$t('webchat.lastYear'), value: 'time__lastYear', condition: {}},
            {label: this.$t('business.weekParticipated'), value: 'time__week__participated', condition: {processMember: this.$store.state.session.sessionId, quickSearch: true}},
            {label: this.$t('business.weekFollowdeAgent'), value: 'time__week__followdeAgent', condition: {searchType: 'myFollowedBusiness', quickSearch: true}},
            {label: this.$t('business.weekCreated'), value: 'time__week__created', condition: {createUser: this.$store.state.session.sessionId, quickSearch: true}}
          ]
          if (this.$store.state.iframeMessage.showBusinessCreateTime) {
            all.splice(7, 0, {label: this.$t('webchat.threeYear'), value: 'time__threeYear', condition: {}})
          }
          let businessType = this.$store.state.business.transCache.businessTypes
          let undeal = [
            {label: this.$t('public.all'), value: '', condition: {flow: ''}},
            ...businessType
          ]
          let my = [
            {label: this.$t('public.all'), value: '', condition: {flow: ''}},
            {label: this.$t('business.laterProcess'), value: 'laterProcess', condition: {laterProcess: true}},
            {label: this.$t('business.myTemp'), value: 'temp', condition: {saveFlag: 'temp'}, sortClass: 'sortClass'},
            ...businessType
          ]
          let selectObj = {all: '', my: '', undeal: ''}
          obj = {undeal, my, all}
          if (res.success) {
            let list = res.data || []
            list.forEach((item) => {
              if(item.type){
                item.condition.customSearch = 'customSearch'
                item.condition.type = item.type
              }
              obj[item.menu].push({label: item.name, value: item._id, condition: item.condition})
              selectObj[item.menu] = (selectObj[item.menu] === '' && item.default === 'true') ? item._id : selectObj[item.menu]
            })
          }
          this.search.business_undeal.isChildren.defaultSelect = selectObj.undeal || ''
          this.search.business_my.isChildren.defaultSelect = selectObj.my || ''
          this.search.business_all.isChildren.defaultSelect = selectObj.all || 'time__week'
          this.search.business_undeal.isChildren.select = obj.undeal
          this.search.business_my.isChildren.select = obj.my
          this.search.business_all.isChildren.select = obj.all
          let flag = this.search[this.activeName].isChildren.select.some((item) => {
            if (this.search[this.activeName].currentSelect.value === item.value) {
              return true
            }
          })
          // 如果当前快捷搜索条件为其中一个自定义快捷搜索是，刷新列表
          // if (!flag && this.search[this.activeName].currentSelect.value) {
          //   this.changeTab(this.activeName, true)
          // }
        })
      },
      removeBadge () {
        // 移除bandage后，快捷搜索
        this.search[this.activeName].isChildren.adv.badgeList = {}
        this.search[this.activeName].partakeAgentRemark = false
        this.search[this.activeName].currentSelect = {value: '', condition: {}}
        this.resetAdvSearch()
        let current = this.search[this.activeName]
        let select = current.currentSelect.value = current.isChildren.defaultSelect || ''
        // let firstQuery = this.$store.state.business.getBusinessFirstQuery
        // this.$store.commit('business/GET_BUSINESS_QUERY', firstQuery)
        this._handlerQuickSelect('')
        this.clearChecked = Math.random()
      },
      defaultSetting () {
        // 设置高级搜索默认时间
        let week = this.searchDataReturn('week')
        this.search.business_all.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
      },
      /*
      * 快捷搜索时间
      * */
      searchDataReturn (value) {
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let startTime = ''
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        if (value === 'week') {
          // 近一周
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'today') {
          // 今天
          startTime = getFormatDateTime(new Date(mtDate)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'yesterday') {
          // 昨天
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 00:00:00'
          endTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 23:59:59'
        } else if (value === 'month') {
          // 近一月
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 29)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'oneYear') {
          let year = nowTime.getFullYear()
          startTime = year + '-01-01 00:00:00'
        } else if (value === 'lastYear') {
          let year = nowTime.getFullYear() - 1
          startTime = year + '-01-01 00:00:00'
          endTime = year + '-12-31 23:59:59'
        } else if (value === 'threeYear') {
          let threeYear = new Date()
          threeYear.setFullYear(nowTime.getFullYear() - 3)
          startTime = getFormatDateTime(threeYear)
        } else {
          endTime = ''
        }
        let searchQuery = {
          createTime$begin: startTime,
          createTime$end: endTime
        }
        return searchQuery
      },
      handlerQuickSelect (value) {
        this.search[this.activeName].isChildren.nomalForm.query = ''
        this.isSelectClick = true
        this.search[this.activeName].currentSelect.value = value
        this.search[this.activeName].isChildren.select.some((item) => {
          if (item.value === value) {
            this.search[this.activeName].currentSelect.condition = deepClone(item.condition)
            return true
          }
        })
        let type = value.split('__')
        if (value === 'time__oneYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-今年'])
        } else if (value === 'time__lastYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-去年'])
        } else if (value === 'time__threeYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-近三年'])
        }
        if (type[0] === 'time') {
          let time = this.searchDataReturn(type[1])
          utilExtend(this.search[this.activeName].currentSelect.condition, time)
          // let start = time.createTime$begin || ''
          // let end = time.createTime$end || ''
          // if (start && end) {
          //   this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [new Date(time.createTime$begin), new Date(time.createTime$end)])
          // } else {
          //   this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [])
          // }
        } else {
          // this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [])
        }
        this.search[this.activeName].partakeAgentRemark = false
        if (this.search[this.activeName].isAdvSearch && value === null) {
          return
        }
        this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
        this.search[this.activeName].isAdvSearch = false
        this.search.isSearch = true
        let self = this
        self.loading = true
        let queryData = deepClone(this.search[self.activeName].isChildren.nomalForm)
        Object.assign(queryData, this.search[this.activeName].currentSelect.condition)
        self.search[self.activeName].pagination.currentPage = 1
        this.$store.state.business.getBusinessFirstQuery.page = 1
        this.$store.state.business.getBusinessFirstQuery.morePage = 1
        queryData.morePage = 1
        queryData.page = 1
        let queryData1 = deepClone(this.$store.state.business.getBusinessFirstQuery)
        if(queryData1.type){
          queryData1.flowquick = {flow:queryData.flow}
        }else{
          queryData1.flow = queryData.flow
        }
        this.getBusiness(this.$store, self.activeName, queryData1)
      },
      _handlerQuickSelect (value) {
        this.search[this.activeName].isChildren.nomalForm.query = ''
        this.isSelectClick = true
        this.search[this.activeName].currentSelect.value = ''
        this.search[this.activeName].isChildren.select.some((item) => {
          if (item.value === value) {
            this.search[this.activeName].currentSelect.condition = deepClone(item.condition)
            return true
          }
        })
        let type = value.split('__')
        if (value === 'time__oneYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-今年'])
        } else if (value === 'time__lastYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-去年'])
        } else if (value === 'time__threeYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-近三年'])
        }
        if (type[0] === 'time') {
          let time = this.searchDataReturn(type[1])
          utilExtend(this.search[this.activeName].currentSelect.condition, time)
          // let start = time.createTime$begin || ''
          // let end = time.createTime$end || ''
          // if (start && end) {
          //   this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [new Date(time.createTime$begin), new Date(time.createTime$end)])
          // } else {
          //   this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [])
          // }
        } else {
          // this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [])
        }
        this.search[this.activeName].partakeAgentRemark = false
        if (this.search[this.activeName].isAdvSearch && value === null) {
          return
        }
        this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
        this.search[this.activeName].isAdvSearch = false
        this.search.isSearch = true
        let self = this
        self.loading = true
        let queryData = deepClone(this.search[self.activeName].isChildren.nomalForm)
        Object.assign(queryData, this.search[this.activeName].currentSelect.condition)
        self.search[self.activeName].pagination.currentPage = 1
        queryData.morePage = 1
        queryData.page = 1
        this.getBusiness(this.$store, self.activeName, queryData)
      },
      tabPanes () {
        let roleNum = this.$store.state.business.roleNum
        let total = this.$store.state.business.total
        let noReadNum = this.$store.state.business.noReadNum
        if (roleNum > 99) {
          roleNum = '99+'
        }
        if (total > 99) {
          total = '99+'
        }
        if (noReadNum > 99) {
          noReadNum = '99+'
        }
        return [
          {name: this.$t('business.undealBusiness') + roleNum, type: 'business_undeal'},
          {name: this.$t('business.myTodo') + noReadNum + '/' + total, type: 'business_my'},
          {name: this.$t('business.allBusiness'), type: 'business_all'}
        ]
      },
      businessRefresh () {
        let query = this.$store.state.business.getBusinessQuery
        this.getBusinessList(query)
      },
      refreshUndealNum () {
        this.$store.dispatch('refreshUndealNum')
      },
      // 批量导出方法
      exportCustom () {
        this.getExportCount().then((_num) => {
          let limitNum = this.$getCache('exportTaskLimit') || {}
          if (limitNum.business && _num > limitNum.business) {
            this.$message.error(this.$t('business.exportBusinessLimit', {length: limitNum.business}))
            return
          }
          // 导出任务 50000
          if (_num > 50000) {
            this.exportDialog.fileType = 'csv'
            this.exportDialog.type = 'task'
            if (!this.exportDialog.agents.length) {
              this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
                this.exportDialog.agents = res.map((item) => {
                  return {value: item._id, label: `${item.displayName}[${item.exten}]`}
                })
              })
            }
            let session = this.$store.state.session
            this.exportDialog.downloadAgents = []
            if (session.user.type !== 'admin') {
              this.exportDialog.downloadAgents.push(session.sessionId)
            }
          } else {
            this.exportDialog.type = 'export'
          }
          this.exportDialog.isShow = true
          this.exportDialog.select = []
          let key = this.$store.state.session.sessionId + 'businessExportHeaders'
          let cacheHeaders = JSON.parse(window.localStorage.getItem(key))
          this.exportDialog.headers.forEach((item) => {
            if (cacheHeaders) {
              cacheHeaders.includes(item.value) && this.exportDialog.select.push(item.value)
            } else if (item.default) {
              this.exportDialog.select.push(item.value)
            }
          })
        })
      },
      deleteTip () {
        if (this.batch.allChecked) {
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              const _num = res.count
              this.handleDeleteTip(_num)
            }
          })
        } else {
          this.handleDeleteTip(this.batch.checkedCount)
        }
      },
      handleDeleteTip (num) {
        this.$confirm(this.$t('business.businessDelete', {num}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.deleteBus(this)
          //删除之后更新左侧菜单栏数量统计
          this.$store.commit('business/REFRESH_MENUBAR',Math.random())
        }).catch(() => {
        })
      },
      deleteBus (self) {
        let data = {}
        if (self.batch.allChecked) {
          data = deepClone(this.$store.state.business.businessCondition)
          if (data.flow) {
            data.flow = typeof data.flow !== 'string' ? (data.flow.$in || []) : data.flow
          }
        } else {
          data = {_id: {$in: self.batch.batchItem}}
        }
        self.$store.dispatch('deleteBusiness', data).then(() => {
          this.$message.success(this.$t('message.deleteSucc'))
          this.businessRefresh()
          this.refreshUndealNum()
        })
      },
      checkNone () {
        let that
        if (self && self.$refs) {
          that = self
        } else {
          that = this
        }
        that.batch.allChecked = false
        that.batch.batchItem = []
        that.batch.isBatchShow = false
        this.$refs.businessTable.clearSelection()
      },
      async batchAssign () {
        // 同一工单类型和工单步骤的工单
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量分配（可点击状态的）'])
        let step = ''
        let isValide = false
        if ((this.qu.flow instanceof Array) && this.qu.flow.length === 1 && this.qu.step) {
          // 高级搜索筛选
          isValide = true
          if((this.qu.step instanceof Array) && this.qu.step.length === 1){
            step = this.qu.step[0]
          }
        }
        if (!isValide) {
          return
        }
        let roles = getStepRoles(step)
        let queues = getStepQueues(step)
        let queueAgents = []
        let roleAgentList = []
        let queueAgentList = []
        roleAgentList = getRoleAgents(roles, true)
        queueAgentList = await getQueueAgents(queues, false)
        let agents = [...new Set(roleAgentList.concat(queueAgentList))]
        if (roles[0] === 'busCreateUser') {
          // 正常情况，不可能进这里，流转到工单创建人的工单会直接填处理人，不会自动分配
          return
        }
        if (this.batch.allChecked) {
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              this.$refs.batchAssign.open({count: _num, condition: this.qu, agents: agents, ids: []})
            }
          })
        } else {
          this.$refs.batchAssign.open({count: this.batch.checkedCount, condition: {}, agents: agents, ids: this.batch.batchItem})
        }
      },
      batchReceive () {
        // 统计埋点
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量领取'])
        if (this.batch.allChecked) {
          // 全选获取总数
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              if (_num > 500) {
                // 大于10000条，提示重新查询
                this.$message.error(this.$t('message.batch_claim_business_max_limit'))
                return
              }
              // 批量领取提醒框
              let data = {total: _num, condition: deepClone(this.qu)}
              delete data.condition.queryCount
              delete data.condition.page
              delete data.condition.morePage
              this.batchReceiveDialog(data)
            }
          })
        } else {
          this.batchReceiveDialog({total: this.batch.checkedCount, ids: this.batch.batchItem})
        }
      },
      batchReceiveDialog (data) {
        data.master = this.$store.state.session.sessionId
        this.$confirm(this.$t('business.batchReceiveTip', {total: data.total || 0}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('batchClaim', data).then((res) => {
            if (res && res.success) {
              let message = res.failCount ? 'business.operateSucOther' : 'business.batchReceiveSuc'
              this.$message.success(this.$t(message))
              this.checkNone()
              this.$store.commit('business/REFRESH_LEFT', Math.random())
              this.businessRefresh()
              this.refreshUndealNum()
            }
          })
        })
      },
      updateGuidanceSuccess () {
        let guidance = this.$getCache('guidance')
        this.getNoviceKeyStatus = guidance || {'businessBatchAssign': true, 'businessBatchExecute': true} // 服务不对，或者是没有这个对象时，默认不显示。webchatSessionLocking为气泡的key
      },
      getExportCount () {
        if (this.batch.allChecked) {
           return this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              return res.count
            }
          })
        } else {
          return Promise.resolve(this.batch.checkedCount)
        }
      },
      exportExcel (type) {
        if (this.exportDialog.select.length === 0) {
          this.$message.error(this.$t('business.exportSelectOne'))
          return
        }
        // 高级搜索条件
        let data = {}
        if (this.batch.allChecked) {
          data = deepClone(this.$store.state.business.businessCondition)
        } else {
          data = {_id: {$in: this.batch.batchItem}}
        }
        if (this.tabType === 'business_undeal' || this.tabType === 'business_my') {
          data.flag = 'kf'
        }
        let headers = []
        let sessionId = this.$store.state.session.sessionId
        this.exportDialog.headers.forEach((item) => {
          if (this.exportDialog.select.indexOf(item.value) !== -1) {
            headers.push(item.value)
          }
        })
        if (type === 'task') {
          let downloadAgents = this.exportDialog.downloadAgents
          if (!downloadAgents.length) {
            return this.$message.error('至少选择一个可下载座席')
          }
          let exportData = {condition: data, headers, downloadAgents}
          if (this.exportType === 'real') {
            exportData.fileType = this.exportDialog.fileType
          }
          this.$store.dispatch('addExportTask', exportData).then((res) => {
            if (res.success) {
              this.checkNone()
              window.localStorage.setItem(sessionId + 'businessExportHeaders', JSON.stringify(headers))
              this.exportDialog.isShow = false
              this.$message.success(this.$t('business.exportExcel50000' + this.exportType))
            }
          })
        } else {
          data.headers = headers
          let _exportObj = {
            name: this.$t('business.exportName') + this.getCurrentDateTime(),
            id: uuid.v1()
          }
          this.$store.commit(gtypes.SET_EXPORTLIST, _exportObj)
          this.$store.dispatch('exportBusiness', data).then((res) => {
            if (res.success) {
              window.localStorage.setItem(sessionId + 'businessExportHeaders', JSON.stringify(headers))
            }
            this.$store.commit(gtypes.DEL_EXPORTLIST, _exportObj)
          })
          this.checkNone()
          this.exportDialog.isShow = false
        }
      },
      getCurrentDateTime () {
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()
        let day = date.getDate()
        let h = date.getHours()
        let m = date.getMinutes()
        let s = date.getSeconds()
        month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
        day = day > 9 ? day : '0' + day
        h = h > 9 ? h : '0' + h
        m = m > 9 ? m : '0' + m
        s = s > 9 ? s : '0' + s
        return year + '-' + month + '-' + day + ' ' + h + '-' + m + '-' + s
      },
      selectionchange (selection) {
        let checkedArr = selection.map(item => item._id)
        this.selectLength = checkedArr.length
        let isBatchShow = checkedArr.length > 0
        let bCheck = checkedArr.length === this.$store.state.business.businessList.count
        this.$set(this.batch, 'allChecked', bCheck)
        // this.batch.allChecked = checkedArr.length === this.$store.state.business.businessList.list.length
        this.batch.batchItem = checkedArr
        this.batch.isBatchShow = isBatchShow
        this.batch.checkedCount = checkedArr.length
      },
      selectionall (arr) {
        this.batch.allChecked = true
        if (this.$store.state.business.businessList.more) {
          this.batch.checkedCount = this.batch.allChecked ? this.$t('public.moreThan2') + this.$store.state.business.businessList.count : 0
        } else {
          if (this.allCount) {
            this.batch.checkedCount = this.allCount
          } else {
            this.batch.checkedCount = this.batch.allChecked ? this.$store.state.business.businessList.count : 0
          }
        }
      },
      selectionallClick () {
        if (!this.batch.allChecked && this.selectLength === 10) {
          this.batch.allChecked = true
          this.selectionall()
        } else {
          this.batch.allChecked = false
          this.$refs.businessTable.selectionallClick()
        }
      },
      routeToMe (isbeforeMount) {
        let query = this.$route.query
        if (query.flag === 'advSearch') {
          this.$store.commit('business/OPERATION_NEW_BUSINESS_SLIDE', { active: query.active, flag: 'selectSide'})
          this.activeName = query.active
          this.$store.commit('BLANK', this.activeName)
          this.search[this.activeName].partakeAgentRemark = false
          let form = this.search[this.activeName].isChildren.adv.form
          for (let key in form) {
            if (key === 'custom') {
              form.custom = {}
            } else if (key === 'flow') {
              form[key] = []
            } else {
              form[key] = null
            }
          }
          this.search[this.activeName].isChildren.adv.form.number = query.busNumber
//          let user = this.$store.state.session.user
          if (query.type === 'attention') {
            // 我关注的工单
            this.search[this.activeName].isChildren.adv.form.searchType = 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')
          } else if (query.type === 'businessJoin') {
            // 我参与处理的工单
            this.search[this.activeName].isChildren.adv.form.searchType = 'myParticipated__' + this.$t('business.myParticipated')
          }
          this.advSearch(false, 1)
        } else if (query.flag === 'toCard') {
          this.isNotify = false
          this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: false})
          this.$store.commit('business/OPERATION_NEW_BUSINESS_SLIDE', query)
        } else if (isbeforeMount) {
          // this.changeTab(this.activeName, true)
        }
      },
      // 批量处理工单
      batchExecute (action, enabled) {
        if (enabled) {
          // 统计埋点
          window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量处理（不可点击状态的）'])
          return
        }
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量处理（可点击状态的）'])
        let promise = null
        // 缓存 工单条件，count，提交时使用
        if (this.batch.allChecked) {
          promise = this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              this.batchBusiness.argu = {total: _num, condition: deepClone(this.qu)}
              delete this.batchBusiness.argu.condition.queryCount
              delete this.batchBusiness.argu.condition.page
              delete this.batchBusiness.argu.condition.morePage
            }
          })
        } else {
          promise = new Promise((resolve) => {
            this.batchBusiness.argu = { total: this.batch.checkedCount, ids: this.batch.batchItem }
            resolve()
          })
        }
        promise.then(() => {
          // 生成工单动作
          this.batchBusiness.operateSelect = []
          this.batchBusiness.show = true   
          let step = null
          if((this.qu.step instanceof Array) && this.qu.step.length === 1){
            step = this.$getCache('businessFlowStep', this.qu.step[0])
          }
          let actions = step && step.actions ? step.actions : []
          let businessRole = []
          let businessQueue = []
          let mixedBizScope = []
          // mixedBizScope 角色或技能组 role之前单角色
          mixedBizScope = this.$store.state.session.user.mixedBizScope ? deepClone(this.$store.state.session.user.mixedBizScope) : deepClone(this.$store.state.session.user.role)
          if (this.tabType === 'business_my') {
            if (this.batch.operatorMy[0].createUser && this.batch.operatorMy[0].createUser === 'myself') {
              mixedBizScope.push('busCreateUser')
            }
          }
          // 符合动作角色或者技能组的坐席都有处理权限
          for (let i = 0; i < actions.length; i++) {
            var actionsItem = actions[i]
            // 技能组
            if(actionsItem.actionAllow){
              if(mixedBizScope) {
                // 只要当前坐席中角色与技能组中有当前步骤技能组的
                if (arrayContainsStr(mixedBizScope, actionsItem.actionQueue)) {
                  // 技能组
                  if (actionsItem.actionQueue.length > 0) {
                    actionsItem.actionQueue.forEach(item=>{
                      businessQueue.push(item)
                    })
                  }
                  this.batchBusiness.operateSelect.push(
                    {
                      value: actionsItem._id,
                      label: actionsItem.name,
                      actionRole: actionsItem.actionRole
                    }
                  )
                }
              }
            } else {
              if(mixedBizScope) {
                // 只要当前坐席中角色中有当前步骤角色的
                if (arrayContainsStr(mixedBizScope, actionsItem.actionRole)) {
                  //兼容老数据，之前是字符串
                  if(!Array.isArray(actionsItem.actionRole)){
                    actionsItem.actionRole = [actionsItem.actionRole]
                  }
                  actionsItem.actionRole.forEach(item=>{
                    businessRole.push(item)
                  })
                  this.batchBusiness.operateSelect.push(
                    {
                      value: actionsItem._id,
                      label: actionsItem.name,
                      actionRole: actionsItem.actionRole
                    }
                  )
                }
              }
            }
          }
        })
      },
      // 选择批量回退
      showTaskBack () {
        this.$refs.batchExecute.open({
          type: 'back',
          title: this.$t('business.returnBusiness'),
          busData: {
            _id: ''
          },
          condition: this.batchBusiness.argu
        })
      },
      // 选择某一工单步骤
      showTaskAction (key) {
        let actionId = key
        let stepId = ''
        if((this.qu.step instanceof Array) && this.qu.step.length === 1){
          stepId = this.qu.step[0]
        }
        let action = getFlowAction(stepId, actionId)
        let nextStepId = action.jumpTo
        let nextStep = getCache('businessFlowStep', nextStepId)
        if (nextStep.type === 'sys') { // 如果下一步是系统步骤，并且没有配置界面，则直接执行。
          let step = getCache('businessFlowStep', stepId)
          action = getFlowStepActionById(step.actions, actionId)
          let fields = action.actionFields
          if (fields.length === 0) {
            // 不填工单信息，直接提交
            let executeData = {actionId: actionId, master: 'sys'}
            this.busCompleteTip(executeData)
            return
          }
        }
        this.$refs.batchExecute.open({
          type: 'approval',
          title: this.$t('business.dealBusiness') + '-' + action.name,
          busData: {
            _id: '',
            stepId: this.qu.step[0],
            flow: this.qu.flow[0],
            actionId: actionId
          },
          condition: this.batchBusiness.argu
        })
      },
      // 流转到系统步骤提醒
      busCompleteTip (executeData) {
        let condition = this.batchBusiness.argu
        this.$confirm(this.$t('business.batchExecuteTip', {total: condition.total || 0}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning'
        }).then(() => {
          condition.data = executeData
          this.$store.dispatch('batchExecute', condition).then((res) => {
            if (res && res.success) {
              this.batchExecuteSuc(res)
            }
          })
        })
      },
      // 批量执行成功
      batchExecuteSuc (res,type) {
        if(type && type == 'back'){
          //批量退回工单需要单独处理message提示
          let msg = '',msgType = '';
          if(res.failCount == res.total){
            //全部不可退回
            msg = 'business.operateBackFail';
            msgType = 'error'
          }else if(res.successCount == res.total){
            //全部可退回
            msg = 'business.operateSuc';
            msgType = 'success'
          }else{
            //部分可退回
            msg = 'business.operateBackSome';
            msgType = 'warning'
          }
          this.$message({
            type:msgType,
            message:this.$t(msg)
          })
        }else{
          let message = res.failCount ? 'business.operateSucOther' : 'business.operateSuc'
          this.$message.success(this.$t(message))
        }
        this.checkNone()
        // 批处理成功后，刷新card
        this.businessRefresh()
        this.refreshUndealNum()
        //执行成功后把批量处理的popover关闭
        this.batchBusiness.show = false;
        this.$store.commit('business/REFRESH_LEFT', Math.random())
        //执行成功后刷新新版工单菜单栏数量统计
        this.$store.commit('business/REFRESH_MENUBAR',Math.random())

      },
      // 批量领取工单
      batchReceive () {
        // 统计埋点
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量领取'])
        if (this.batch.allChecked) {
          // 全选获取总数
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              if (_num > 500) {
                // 大于10000条，提示重新查询
                this.$message.error(this.$t('message.batch_claim_business_max_limit'))
                return
              }
              // 批量领取提醒框
              let data = {total: _num, condition: deepClone(this.qu)}
              delete data.condition.queryCount
              delete data.condition.page
              delete data.condition.morePage
              this.batchReceiveDialog(data)
            }
          })
        } else {
          this.batchReceiveDialog({total: this.batch.checkedCount, ids: this.batch.batchItem})
        }
      },
      // 批量领取弹框确认
      batchReceiveDialog (data) {
        data.master = this.$store.state.session.sessionId
        this.$confirm(this.$t('business.batchReceiveTip', {total: data.total || 0}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('batchClaim', data).then((res) => {
            if (res && res.success) {
              let message = res.failCount ? 'business.operateSucOther' : 'business.batchReceiveSuc'
              this.$message.success(this.$t(message))
              this.checkNone()
              this.businessRefresh()
              this.refreshUndealNum()
              this.$store.commit('business/REFRESH_LEFT', Math.random())
            }
          })
        })
      },
      batchAssignSuc () {
        this.checkNone()
        // this.$store.dispatch('refreshUndealNum')
        this.refreshUndealNum()
        this.$store.commit('business/REFRESH_LEFT', Math.random())
      },
      listenerFun (e) {
        if (this.$refs.popover && !this.$refs.popover.$el.contains(e.target)) {
          this.batchBusiness.show = false
        }
      },
      noChange () {}
    },
    deactivated () {
      // this.$refs.CustomSearchDialog.handleClose()
    },
    beforeMount () {
      this.refreshCustomSearch()
      // this.$store.dispatch('getCache', {type: 'agents'}).then(() => {
      //   this.search()
      // })
      // 批量处理
      if (isHasFunc('func_task_delete', this.$store.state.session.user)) {
        this.batch.operatorCommon.push({name: 'public.delete', class: 'iconfont icon-shanchu', action: 'deleteTip'})
      }
      if (isHasFunc('func_task_export', this.$store.state.session.user)) {
        this.batch.operatorCommon.push({name: 'public.export', class: 'icon-daochu1', action: 'exportExcel'})
//        this.batch.operator.push({name: 'business.exportTask', class: 'icon-piliang', action: 'exportTask'})
      }
      if (isHasFunc('func_task_assign', this.$store.state.session.user)) {
        this.batch.operatorUndeal.push({name: 'business.batchAssign', class: 'icon-fenpei', action: 'batchAssign', tooltipContent: this.$t('business.assignSearchTip'), enabled: true})
      }
      Promise.all([this.$store.dispatch('getCache', {type: 'businessFlowField'}), this.$store.dispatch('getCache', {type: 'options'}), this.$store.dispatch('getCache', {type: 'custTmpls'})]).then(() => {
        getBusinessFlow(this.$store).then(() => {
          let arr = ['business_undeal', 'business_my', 'business_all']
          arr.forEach((tabPane) => {
            this.search[tabPane].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'flow') {
                item.data = this.$store.state.business.transCache.businessTypes
              }
            })
          })
          this.refreshCustomSearch().then(() => {
            this.currentPage = true
            // this.routeToMe(true)
          })
        })
      })
      this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
        let agent = res || []
        let data = [{label: this.$t('public.all'), value: ''}]
        let data2 = [{label: this.$t('public.all'), value: ''}]
        if (agent) {
          for (let i = 0; i < agent.length; i++) {
            if (agent[i]._id !== this.$store.state.session.sessionId) {
              data.push({label: agent[i].displayName, value: `${agent[i]._id}__${agent[i].displayName}`})
            }
            data2.push({label: agent[i].displayName, value: `${agent[i]._id}__${agent[i].displayName}`})
          }
        }
        let arr = ['business_undeal', 'business_my', 'business_all']
        arr.forEach((item) => {
          let nameType = item
          this.search[item].isChildren.adv.advSearchOptions.localed.forEach((item) => {
            if (item.name === 'processMember' && nameType === 'business_undeal') {
              item.data = data2
            } else if (item.name === 'processMember') {
              item.data = data
            }
          })
        })
      })
      this.$store.dispatch('getAdvSearchConfig', {searchType: 'BusinessCardGroup'}).then((config) => {
        this.formItemsConfigs = config || {}
      })
      this.updateGuidanceSuccess()
    },
    watch: {
      '$store.state.business.getBusinessQuery' (newQuery) {
        this.activeName = 'business_' + newQuery.menu
        this.queryObj = newQuery
        let _qu = deepClone(newQuery)
        _qu.queryCount = true
        this.qu = _qu
        this.quAction = 'queryAllBusinessCount'
        this.pagination.currentPage = 1
        this.getBusinessList(newQuery)
        if (!this.isSelectClick) {
          this.search[this.activeName].currentSelect = {value: undefined, condition: {}}
        } else {
          this.isSelectClick = false
        }
        if (!this.isAdvSearchClick) {
          this.search[this.activeName].isChildren.adv.badgeList = {}
        }
        this.isAdvSearchClick = false
      },
      '$store.state.business.getBusinessFirstQuery' () {
        this.resetAdvSearch()
        this.search[this.activeName].isChildren.nomalForm.query = ''
      },
      '$store.state.business.currentBusinessType' (newType) {
        this.activeName = newType
      },
      'batch.isBatchShow' (nowV) {
        this.$store.commit('business/SET_IS_NOEDITING', nowV)
        if (nowV === true && this.activeName === 'business_undeal') {
          // 有批量分配权限，且条件满足
          if (this.batch.operatorUndeal.length === 2 && this.qu.step && this.qu.step.length ==1) {
            this.batch.operatorUndeal[1].enabled = false
          } else if (this.batch.operatorUndeal.length === 2) {
            // 有批量处理权限，且条件不满足
            this.batch.operatorUndeal[1].enabled = true
          }
          this.batch.operator = this.batch.operatorCommon.concat(this.batch.operatorUndeal)
        } else if (nowV === true && this.activeName === 'business_my') {
          // 选择了某一工单类型和步骤
          let step = null
          if((this.qu.step instanceof Array) && this.qu.step.length === 1){
            step = this.$getCache('businessFlowStep', this.qu.step[0]) || {}
            // 如果step为第一步，不满足批处理
            if (step.isBegin) {
              // 如果是开始步骤 toottip提醒内容不同
              this.batch.operatorMy[0].tooltipContent = this.$t('business.executeSearchTip1')
            }
            this.batch.operatorMy[0].enabled = step.isBegin
          }else if (this.batch.operatorMy.length) {
            this.batch.operatorMy[0].enabled = true
            this.batch.operatorMy[0].tooltipContent = this.$t('business.executeSearchTip')
          }
          this.batch.operator = this.batch.operatorCommon.concat(this.batch.operatorMy)
        } else if (nowV === true && this.activeName !== 'business_undeal') {
          this.batch.operator = this.batch.operatorCommon
        }
      },
      noticeBusJump () {
        let data = this.$store.state.noticeBusJump
        this.isNotify = true
        if (data.module === 'business' && this.currentPage) {
          this.routeToMe()
        }
      },
      '$store.state.business.isRefreshBusinessView' () {
        this.pagination.currentPage = 1
        this.businessRefresh()
        this.refreshUndealNum()
      }
    },
    computed: {
      businessTypes () {
        let obj =  { "value": "", "label": "全部", "condition": {} }
        let businessTypes = deepClone(this.$store.state.business.transCache.businessTypes)
        businessTypes.unshift(obj)
        return businessTypes
      },
      noticeBusJump () {
        return this.$store.state.noticeBusJump.random
      },
      cardListRender () {
        // 防止getCache没取回就执行computed
        if (this.cardloading) {
          return []
        }
        let hh = []
        if(this.laterProcessData.length>0){
          hh = this.laterProcessData || []
        }else{
          hh = this.tableData || []
        }
        let items = []
        for (let i = 0; i < hh.length; i++) {
          let item = hh[i]
          let one = {}
          one.userName = this.name(item)
          // one.custStatus = this.custStatus(item.cust_status)
          one.businessType = this.businessType(item)
          one.agentAfter = this.agentAfter(item.master)
          one.agentBefore = this.agentBefore(item.createUser)
          one.businessStep = this.businessStep(item.flow, item.status, item.step)
          one.createTime = timeFormat(item.createTime, 'card')
          one._id = item._id
          one.customer = item.customer
          one.processTimeout = item.processTimeout
          one.priority = item.priority
          one.follow = 'none'
          one.stepId = item.step
          one.noRead = item.isReadFlag === false
          // 稍后处理
          one.laterProcess = this.activeName === 'business_my' && item.laterProcess
          one.laterProcessColor = this.activeName === 'business_my' && item.laterProcessColor
          if (item.followedAgents && item.followedAgents.indexOf(this.sessionId) !== -1) {
            one.follow = ''
          }
          items.push(one)
        }
        return items
      },
      totalPage () {
        return Math.ceil(this.pagination.count / 10) || 0
      },
      businessOperation () {
        return this.$store.state.business.showNewBusinessRouterBox
      },
      navMenuState () {
        return this.$store.state.navMenuState || false
      },
      isNoediting () {
        return this.$store.state.business.isNoediting
      }
    }
  }
  function getBusinessFlowStep (store, flowId) {
    return store.dispatch('getCache', {type: 'businessFlow', id: flowId})
  }
  function getBusinessFlow (store) {
    return store.dispatch('getBusinessFlow')
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .batch-step
    font-size 12px
    line-height 27px
    text-align center
    &:hover
      background-color #f5f7fa
      cursor pointer
      color $c-main
  .batch-step.pink
    color $c-pink
  .custom-export
    label
      visibility visible
      margin 0 15px 15px 0
    .el-checkbox
      visibility visible
    .tips
      margin-bottom 15px
      color $c-prompt
    .checkbox-tooltip
      color $c-prompt
      font-size 14px
    .export-content
      padding 10px 0 20px
    .export-content__item
      display flex
      align-content center
      .export-content__label
        margin-right 15px
    .footer
      text-align center
  .batch
    width calc(100vw - 255px)
  .navMenuState
    width calc(100vw - 312px)
  .table-wrap
    height 100%
  .table-wrap-top
    position relative
    .table-wrap-top-mask
      position absolute
      width 100%
      height 100%
      background rgba(255,255,255,0.3)
      cursor not-allowed
      z-index 1000
    .table-wrap-top-left
      display flex
      align-items center
    .table-wrap-top-right
      .paginationNew
        position relative
        bottom 0
        box-shadow none
        border-right 0
        background none
    .table-wrap-add
      span
        margin-right 10px
        color #4C9EE8
        font-size 12px
        cursor pointer
        .iconfont
          font-size 12px
    .table-wrap-top-search-input
      margin 0
    display flex
    justify-content space-between
    align-items center
    margin-bottom 10px
    .table-wrap-top-search
      display flex
      align-items center
      position relative
  .custom-search
    height 100%
    position relative
  h4
    line-height 40px
    border-bottom 1px solid $c-border1
    padding-left 10px
    font-weight bold
  .table-wrap
    padding 30px 20px
    overflow auto
</style>
<style lang="stylus">
  .newBusinessSideBar
    .toggle-btn
      line-height: 28px
      width: 26px
      border: 1px solid #dcdfe6
      height: 30px
      display: inline-block
      box-sizing: border-box
      top: 1px
      color: #9a9a9a
      text-align: center
      margin-left: -1px
      background-color: #fff
      border-radius: 0 4px 4px 0
      cursor: pointer
</style>
